﻿using ComTools.File;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace MSSQL.CommandTool
{
	/// <summary>
	/// 数据命令操作对象
	/// </summary>
	public static class DataCommandManager
	{
		#region 变量

		/// <summary>
		/// SQL命令配置文件全路径
		/// </summary>
		private static string commandFileConfigFullName;

		/// <summary>
		/// SQL命令文件全路径
		/// </summary>
		private static string conmandsDirectoryFullPath;

		/// <summary>
		/// SQL命令集合
		/// </summary>
		private static Dictionary<string, DataCommandInstance> commandInstanceList;

		/// <summary>
		/// 侦听文件系统对象
		/// </summary>
		private static FileSystemWatcher sWatcher = new FileSystemWatcher()
		{
			NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite
		};

		/// <summary>
		/// 同步锁
		/// </summary>
		private static readonly object locker = new object();

		/// <summary>
		/// command配置文件的路径名
		/// </summary>
		private const string commandFileConfigPath = @"CommandTool\DataBaseConfig\DataCommandFiles.config";

		/// <summary>
		/// command文件存放的文件夹路径
		/// </summary>
		private const string conmandsDirectoryPath = @"CommandTool\Commands\";

		#endregion

		static DataCommandManager()
		{
			string rootDic = string.Empty;

			try
			{
				rootDic = HttpRuntime.BinDirectory;
			}
			catch
			{
				rootDic = AppDomain.CurrentDomain.BaseDirectory;
			}

			commandFileConfigFullName = string.Format("{0}{1}", rootDic, commandFileConfigPath);
			conmandsDirectoryFullPath = string.Format("{0}{1}", rootDic, conmandsDirectoryPath);

			sWatcher.Changed += (s, e) => { InitDataCommandList(); };
			sWatcher.Path = Path.GetDirectoryName(conmandsDirectoryFullPath);
			InitDataCommandList();
			sWatcher.EnableRaisingEvents = true;
		}

		/// <summary>
		/// 获取命令文件
		/// </summary>
		/// <returns>命令文件集合</returns>
		private static DataCommandFiles GetDataCommandFileList()
		{
			return XmlEntitySerializer.DeserilizeFromXml<DataCommandFiles>(commandFileConfigFullName);
		}

		/// <summary>
		/// 初始化命令集合
		/// </summary>
		private static void InitDataCommandList()
		{
			lock (locker)
			{
				commandInstanceList = new Dictionary<string, DataCommandInstance>();

				// 获取命令集合
				var files = GetDataCommandFileList();

				foreach (var fileInstance in files.InstanceList)
				{
					var commands = XmlEntitySerializer.DeserilizeFromXml<DataCommands>(string.Format("{0}{1}", conmandsDirectoryFullPath, fileInstance.FilePath));

					if (commands == null) continue;
					foreach (var commandInstance in commands.InstanceList)
					{

						var count = commandInstanceList.Count(p => p.Key.Equals(commandInstance.Name));
						if (count > 1)
						{
							throw new AggregateException("已经加入相同的键:" + commandInstance.Name);
						}
						else
						{
							commandInstanceList.Add($"{commandInstance.Name}:{commandInstance.UseCase}", commandInstance);
						}
					}
				}
			}
		}

		/// <summary>
		/// 获取SQL命令
		/// </summary>
		/// <param name="name">命令的名称</param>
		/// <param name="useCase">用例的名称</param>
		/// <returns>SQL命令</returns>
		public static string GetSQLCommand(string name, string useCase)
		{
			try
			{
				var key = $"{name}:{useCase}";
				if (commandInstanceList.ContainsKey(key))
				{
					var commandInstance = commandInstanceList[key];
					var connType = DatabaseManager.GetDatabase(commandInstance.Database).Type;
					return commandInstance.CommandText;
				}
				else
				{
					throw new ArgumentException($"Command name({key}) not found.");
				}
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
	}
}
